package com.yuke.cloud.service.uac.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.yuke.cloud.common.base.constant.GlobalConstant;
import com.yuke.cloud.common.base.dto.LoginAuthDto;
import com.yuke.cloud.common.base.enums.ErrorCodeEnum;
import com.yuke.cloud.common.core.config.AsyncTaskExecutorConfiguration;
import com.yuke.cloud.common.core.enums.LogTypeEnum;
import com.yuke.cloud.common.core.mq.RabbitMetaMessage;
import com.yuke.cloud.common.core.support.BaseService;
import com.yuke.cloud.common.core.utils.RequestUtil;
import com.yuke.cloud.common.security.core.SecurityUser;
import com.yuke.cloud.common.util.PubUtils;
import com.yuke.cloud.common.util.PublicUtil;
import com.yuke.cloud.common.util.RandomUtil;
import com.yuke.cloud.common.util.RedisKeyUtil;
import com.yuke.cloud.service.api.cmc.service.CmcFeignApi;
import com.yuke.cloud.service.api.smc.dto.ShopInfoDto;
import com.yuke.cloud.service.api.smc.service.SmcFeignApi;
import com.yuke.cloud.service.api.uac.dto.WarehouseAdminUserDto;
import com.yuke.cloud.service.api.uac.exceptions.UacBizException;
import com.yuke.cloud.service.api.wmc.dto.WarehouseInfoDto;
import com.yuke.cloud.service.api.wmc.service.WmcStorageFeignApi;
import com.yuke.cloud.service.uac.dao.AccUserMapper;
import com.yuke.cloud.service.uac.dao.AccUserRoleMapper;
import com.yuke.cloud.service.uac.dto.*;
import com.yuke.cloud.service.uac.entity.*;
import com.yuke.cloud.service.uac.enums.AccUserSourceEnum;
import com.yuke.cloud.service.uac.enums.UacEmailTemplateEnum;
import com.yuke.cloud.service.uac.manager.UserManager;
import com.yuke.cloud.service.uac.mq.producer.EmailProducer;
import com.yuke.cloud.service.uac.service.*;
import com.yuke.cloud.service.uac.utils.Md5Util;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.task.TaskExecutor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;


/**
 * Created by wg on 2018/09/11.
 */
@Slf4j
@Service
@ComponentScan(basePackageClasses = {AsyncTaskExecutorConfiguration.class})
@Transactional
public class AccUserServiceImpl extends BaseService<AccUser> implements AccUserService {
    @Resource
    private AccUserMapper accUserMapper;

    @Resource
    private AccPermissionService accPermissionService;

    @Resource
    private AccUserTokenService accUserTokenService;
    @Resource
    private TaskExecutor taskExecutor;

    @Resource
    AccUserGroupService accUserGroupService;
    @Resource
    private AccEmployeeGroupService accEmployeeGroupService;
    @Resource
    AccUserRoleService accUserRoleService;

    @Resource
    private OpcRpcService opcRpcService;

    @Resource
    private AccLogService accLogService;

    @Resource
    private UserManager userManager;

    @Resource
    private EmailProducer emailProducer;

    @Resource
    private RedisTemplate<Object, Object> redisTemplate;

    @Resource
    private RedisService redisService;

    @Resource
    private AccDeliveryAddressService accDeliveryAddressService;

    @Resource
    private AccUserRoleMapper accUserRoleMapper;

    @Resource
    private AccUserInfoService accUserInfoService;

    @Resource
    private CmcFeignApi cmcFeignApi;

    @Resource
    private SmcFeignApi smcFeignApi;

    @Resource
    private WmcStorageFeignApi wmcStorageFeignApi;

    @Value("${yuke.auth.active-user-url}")
    private String activeUserUrl;

    //保存用户（暂不用该方法）
    public int saveUser(AccUser user) {

        int result;

        if (null == user.getUserId()) {  //新增后台用户
            //判断后台用户是否有相同用户ID
            if (existUserByLoginName(user.getLoginName())) {
                throw new UacBizException(ErrorCodeEnum.UAC10011025, user.getLoginName());
            }

            Long userId = super.generateId();
            user.setUserId(userId);

            //密码需要加密
            user.setUserPassword(Md5Util.encrypt(user.getUserPassword()));
            result = this.save(user);
        } else {
            result = this.update(user);
        }

        return result;
    }

    //根据用户ID删除用户
    public int deleteUserById(Long userId) {

        Preconditions.checkArgument(userId != null, "用户id为空");
        Preconditions.checkArgument(!Objects.equals(userId, GlobalConstant.Sys.SUPER_MANAGER_USER_ID), "超级管理员不能删除");

        // 判断用户是否存在
        AccUser user = accUserMapper.selectByPrimaryKey(userId);
        if (PublicUtil.isEmpty(user)) {
            throw new UacBizException(ErrorCodeEnum.UAC10011011, userId);
        }

        //删除该用户与角色绑定的表
        accUserRoleService.deleteUserRoleByUserId(userId);

        //删除该用户与组绑定的表
        accUserGroupService.deleteUserGroupByUserId(userId);

        return mapper.deleteByPrimaryKey(userId);
    }

    //判断用户是否有相同用户ID的
    private Boolean existUserByLoginName(String loginName) {

        Example example = new Example(AccUser.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("loginName", loginName);
        int result = accUserMapper.selectCountByExample(example);
        if (result > 0) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public AccUser findByLoginName(String loginName) {
        logger.info("findByLoginName - 根据用户名查询用户信息. loginName={}", loginName);
        AccUser accUser = accUserMapper.findByLoginName(loginName);
        logger.info("Leave--findByLoginName - 根据用户名查询用户信息. loginName={}", JSON.toJSONString(accUser));
        return accUser;
    }

    @Override
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public AccUser findUserInfoByUserId(Long userId) {
        return accUserMapper.selectUserInfoByUserId(userId);
    }

    @Override
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public AccUser findByOpenId(String openId) {

        AccUser accUser = accUserMapper.findByOpenId(openId);

        return accUser;
    }

    @Override
    public Collection<GrantedAuthority> loadUserAuthorities(Long userId) {

        // mod by wg 20181221 权限会放在token的payload中，如果权限的过多，则会导致payload很长，因此改成获取角色方式
//        List<AccPermission> ownAuthList = accPermissionService.getOwnPermissionListByUserId(userId);
//        List<GrantedAuthority> authList = Lists.newArrayList();
//        for (AccPermission permission : ownAuthList) {
//            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getUrl());
//            authList.add(grantedAuthority);
//        }
//        return authList;

        List<AccUserRole> ownAuthList = accUserRoleService.listByUserId(userId);
        List<GrantedAuthority> authList = Lists.newArrayList();
        for (AccUserRole accUserRole : ownAuthList) {
            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(accUserRole.getRoleId().toString());
            authList.add(grantedAuthority);
        }
        return authList;
    }

    @Override
    public int updateUser(AccUser accUser) {
        logger.info("更新用户信息 accUser={}", accUser);
        int updateResult = accUserMapper.updateByPrimaryKeySelective(accUser);
        if (updateResult < 1) {
            logger.info("用户【 {} 】修改用户信息失败", accUser.getUserId());
        } else {
            logger.info("用户【 {} 】修改用户信息成功", accUser.getUserId());
        }
        return updateResult;
    }

    @Override
    public AccUser findUserInfoByLoginName(final String loginName) {
        return accUserMapper.findUserInfoByLoginName(loginName);
    }

    @Override
    public void handlerLoginData(OAuth2AccessToken token, final SecurityUser principal, HttpServletRequest request) {
        logger.info("handlerLoginData的参数SecurityUser principal={}", principal);
        final UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
        //获取客户端操作系统
        final String os = userAgent.getOperatingSystem().getName();
        //获取客户端浏览器
        final String browser = userAgent.getBrowser().getName();
        final String remoteAddr = RequestUtil.getRemoteAddr(request);
        // 根据IP获取位置信息
        final String remoteLocation = opcRpcService.getLocationById(remoteAddr);
        final String requestURI = request.getRequestURI();

        AccUser accUser = new AccUser();
        Long userId = principal.getUserId();
        accUser.setLastLoginIp(remoteAddr);
        accUser.setUserId(userId);
        accUser.setLastLoginTime(new Date());
        accUser.setLastLoginLocation(remoteLocation);
        LoginAuthDto loginAuthDto = new LoginAuthDto(userId, principal.getLoginName(), principal.getNickName(), principal.getGroupId(), principal.getGroupName());
        // 记录token日志
        String accessToken = token.getValue();
        String refreshToken = token.getRefreshToken().getValue();
        accUserTokenService.saveUserToken(accessToken, refreshToken, loginAuthDto, request, false, null);
        // 记录最后登录信息
        taskExecutor.execute(() -> this.updateUser(accUser));
        // 记录操作日志
        AccLog log = new AccLog();
        log.setGroupId(principal.getGroupId());
        log.setGroupName(principal.getGroupName());
        log.setIp(remoteAddr);
        log.setLocation(remoteLocation);
        log.setOs(os);
        log.setBrowser(browser);
        log.setRequestUrl(requestURI);
        log.setLogType(LogTypeEnum.LOGIN_LOG.getType());
        log.setLogName(LogTypeEnum.LOGIN_LOG.getName());

        taskExecutor.execute(() -> accLogService.saveLog(log, loginAuthDto));
    }

    @Override
    public AccUser findByMobileNo(String mobileNo) {
        return accUserMapper.findByMobileNo(mobileNo);
    }

    @Override
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public boolean checkLoginName(String loginName) {
        Preconditions.checkArgument(!StringUtils.isEmpty(loginName), ErrorCodeEnum.UAC10011007.msg());

        AccUser accUser = new AccUser();
        accUser.setLoginName(loginName);
        int result = 1;
        try {
            result = accUserMapper.selectCount(accUser);
        } catch (Exception e) {
            logger.error(" 验证用户名是否存在,出现异常={}", e.getMessage(), e);
        }
        return result < 1;
    }

    @Override
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public boolean checkEmail(String email) {
        Preconditions.checkArgument(!StringUtils.isEmpty(email), "email不能为空");

        AccUser accUser = new AccUser();
        accUser.setEmail(email);
        int result = 1;
        try {
            result = accUserMapper.selectCount(accUser);
        } catch (Exception e) {
            logger.error(" 验证email是否存在,出现异常={}", e.getMessage(), e);
        }
        return result < 1;
    }

    @Override
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public boolean checkMobileNo(String mobileNo) {
        Preconditions.checkArgument(!StringUtils.isEmpty(mobileNo), "手机号码不能为空");

        AccUser accUser = new AccUser();
        accUser.setMobile(mobileNo);
        int result = 1;
        try {
            result = accUserMapper.selectCount(accUser);
        } catch (Exception e) {
            logger.error(" 验证手机号码是否存在,出现异常={}", e.getMessage(), e);
        }
        return result < 1;
    }

    @Override
    public void resetLoginPwd(Long userId, LoginAuthDto loginAuthDto) {
        if (userId == null) {
            throw new UacBizException(ErrorCodeEnum.UAC10011001);
        }
        AccUser accUser = this.queryByUserId(userId);
        if (accUser == null) {
            logger.error("找不到用户. userId={}", userId);
            throw new UacBizException(ErrorCodeEnum.UAC10011003, userId);
        }

        Preconditions.checkArgument(!StringUtils.isEmpty(accUser.getEmail()), "邮箱地址不能为空");

        // mod by wg 20190528
//        String newLoginPwd = RandomUtil.createComplexCode(8);
        String newLoginPwd = RandomUtil.createNumberCode(8);
        AccUser update = new AccUser();
        update.setUserId(accUser.getUserId());
        update.setUserPassword(Md5Util.encrypt(newLoginPwd));
        Boolean isChangedPwd = false;
        update.setIsChangedPwd(isChangedPwd);

        Map<String, Object> param = Maps.newHashMap();
        param.put("loginName", accUser.getLoginName());
        param.put("newLoginPwd", newLoginPwd);
        param.put("dateTime", DateUtil.formatDateTime(new Date()));

        Set<String> to = Sets.newHashSet();
        to.add(accUser.getEmail());

        final RabbitMetaMessage mqMessageData = emailProducer.sendEmailMq(to, UacEmailTemplateEnum.RESET_LOGIN_PWD, param);
        try {
            userManager.resetLoginPwd(mqMessageData, update);
        } catch (Exception e) {
            logger.error("重设密码失败，error={}", e.getMessage());
        }

    }

    @Override
    public void resetLoginPwd(ResetLoginPwdDto resetLoginPwdDto) {
        String confirmPwd = resetLoginPwdDto.getConfirmPwd();
        String newPassword = resetLoginPwdDto.getNewPassword();
        String resetPwdKey = resetLoginPwdDto.getResetPwdKey();

        Preconditions.checkArgument(!StringUtils.isEmpty(newPassword), ErrorCodeEnum.UAC10011014.msg());
        Preconditions.checkArgument(!StringUtils.isEmpty(confirmPwd), ErrorCodeEnum.UAC10011009.msg());
        Preconditions.checkArgument(!StringUtils.isEmpty(resetPwdKey), "链接已失效");
        Preconditions.checkArgument(newPassword.equals(confirmPwd), "两次输入密码不一致");

        String resetPwdTokenKey = RedisKeyUtil.getResetPwdTokenKey(resetPwdKey);
        AccUser accUser = (AccUser) redisTemplate.opsForValue().get(resetPwdTokenKey);

        if (StringUtils.isEmpty(accUser)) {
            throw new UacBizException(ErrorCodeEnum.UAC10011028);
        }

        LoginAuthDto loginAuthDto = new LoginAuthDto();
        loginAuthDto.setUserName(accUser.getUserName());
        loginAuthDto.setLoginName(accUser.getLoginName());
        loginAuthDto.setUserId(accUser.getUserId());

        AccUser update = new AccUser();
        update.setUserPassword(Md5Util.encrypt(newPassword));
        update.setUserId(accUser.getUserId());
        // 该用户已经修改过密码
        update.setIsChangedPwd(true);
        update.setUpdateTime(new Date());

        int result = accUserMapper.updateByPrimaryKeySelective(update);
        if (result < 1) {
            throw new UacBizException(ErrorCodeEnum.UAC10011029);
        }
        redisTemplate.delete(resetPwdTokenKey);
    }

    @Override
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public AccUser queryByUserId(Long userId) {
        logger.info("queryByUserId - 根据用户查询用户信息接口. userId={}", userId);
        AccUser accUser = accUserMapper.selectByPrimaryKey(userId);
        if (PublicUtil.isNotEmpty(accUser)) {
            accUser.setUserPassword("");
        }
        return accUser;
    }

    @Override
    public void register(UserRegisterDto registerDto) {
        // 校验注册信息
        validateRegisterInfo(registerDto);
        String mobileNo = registerDto.getMobileNo();
        String email = registerDto.getEmail();
        Date row = new Date();
        // 封装注册信息
        long id = generateId();
        AccUser accUser = new AccUser();
        accUser.setLoginName(registerDto.getLoginName());
        accUser.setUserName(registerDto.getLoginName());
        accUser.setUserPassword(Md5Util.encrypt(registerDto.getLoginPwd()));
        accUser.setMobile(mobileNo);
        accUser.setPayPassword(Md5Util.encrypt(mobileNo.substring(5, 11)));//20191216 设置支付密码初始值为手机号码后6位
        //accUser.setStatus(AccUserStatusEnum.DISABLE.getValue());
        // 默认为激活 mod by wg 20181201
//        accUser.setIsEnable(false);
        accUser.setIsEnable(true);
        accUser.setUserSource(AccUserSourceEnum.REGISTER.getKey());
        accUser.setCreateTime(row);
        accUser.setUpdateTime(row);
        accUser.setEmail(email);
        accUser.setUserId(id);
        accUser.setType(GlobalConstant.Sys.USER_TYPE_CUSTOMER.byteValue());  // 注册时默认初始用户类型为普通客户

        // 注册时默认初始用户不为公司用户
        accUser.setIsEmployee(false);

        // add by wg 20190422 用户注册时增加推荐人或推荐店铺ID
        if (registerDto.getReferenceId() != null && registerDto.getReferenceId() > 0) {
            accUser.setReferenceId(registerDto.getReferenceId());
        } else if (registerDto.getReferenceShopId() != null && registerDto.getReferenceShopId() > 0) {
            accUser.setReferenceShopId(registerDto.getReferenceShopId());
        }

        // 暂时屏蔽掉邮件激活功能 mod by wg 20181201
        accUserMapper.insertSelective(accUser);  // 如果发送邮件激活，则此处注释，在发送邮件后会写入数据库

        // 绑定一个访客角色默认值
        accUserRoleService.saveRoleUser(id, GlobalConstant.Sys.CONSUMER_ROLE_ID);

        AccUserGroup groupUser = new AccUserGroup();

        groupUser.setUserId(id);
        List<AccUserGroup> accUserGroupList = accUserGroupService.select(groupUser);
        if (accUserGroupList == null || accUserGroupList.size() < 1) {
            //groupUser.setEmployeeCode(user.getEmployeeCode());
            groupUser.setGroupId(GlobalConstant.Sys.GROUP_CUSTOMER);
            System.out.println("注册时regist-> user.getGroupId()，默认填入4->accUserGroupService.save(groupUser);");
            log.info("注册时regist-> user.getGroupId()，默认填入4->accUserGroupService.save(groupUser);");
            logger.info("注册时regist-> user.getGroupId()，默认填入4->accUserGroupService.save(groupUser);");
            accUserGroupService.save(groupUser);
        }


//        // 发送激活邮件
//        String activeToken = PubUtils.uuid() + super.generateId();
//        redisService.setKey(RedisKeyUtil.getActiveUserKey(activeToken), email, 1, TimeUnit.DAYS);
//
//        Map<String, Object> param = Maps.newHashMap();
//        param.put("loginName", registerDto.getLoginName());
//        param.put("email", registerDto.getEmail());
//        param.put("activeUserUrl", activeUserUrl + activeToken);
//        param.put("dateTime", DateUtil.formatDateTime(new Date()));
//
//        Set<String> to = Sets.newHashSet();
//        to.add(registerDto.getEmail());
//
//        RabbitMetaMessage mqMessageData = emailProducer.sendEmailMq(to, UacEmailTemplateEnum.ACTIVE_USER, param);
//        try {
//            userManager.register(mqMessageData, accUser);
//        } catch (Exception e) {
//            logger.error("注册用户失败，error={}", e.getMessage());
//        }
    }

    @Override
    public void registerEmployee(UserRegisterDto registerDto) {
        // 校验注册信息
        validateRegisterInfo(registerDto);
        String mobileNo = registerDto.getMobileNo();
        Date row = new Date();
        // 封装注册信息
        long id = generateId();
        AccUser accUser = new AccUser();
        accUser.setUserId(id);
        accUser.setLoginName(registerDto.getLoginName());
        accUser.setUserName(registerDto.getLoginName());
        accUser.setMobile(mobileNo);
        accUser.setUserPassword(Md5Util.encrypt(registerDto.getLoginPwd()));
        //20191216 设置支付密码初始值为手机号码后6位
        accUser.setPayPassword(Md5Util.encrypt(mobileNo.substring(5, 11)));
        accUser.setIsEnable(true);
        accUser.setUserSource(AccUserSourceEnum.REGISTER.getKey());
        accUser.setCreateTime(row);
        accUser.setUpdateTime(row);
        // 注册时默认初始用户类型为普通客户
        accUser.setType(GlobalConstant.Sys.USER_TYPE_CUSTOMER.byteValue());
        accUser.setIsEmployee(true);
        accUserMapper.insertSelective(accUser);

        // 绑定一个访客角色默认值
        accUserRoleService.saveRoleUser(id, GlobalConstant.Sys.CONSUMER_ROLE_ID);

        if (registerDto.getEmployeeType().equals((byte)0)){
            accUserRoleService.saveRoleUser(id, GlobalConstant.Sys.DEPARTMENT_ADMIN_ROLE_ID);
        }else if (registerDto.getEmployeeType().equals((byte)1)){
            accUserRoleService.saveRoleUser(id, GlobalConstant.Sys.DEPARTMENT_SALER_ROLE_ID);
        }else if (registerDto.getEmployeeType().equals((byte)2)){
            accUserRoleService.saveRoleUser(id, GlobalConstant.Sys.DEPARTMENT_DRIVER_ROLE_ID);
        }

        AccUserGroup groupUser = new AccUserGroup();
        groupUser.setUserId(id);
        List<AccUserGroup> accUserGroupList = accUserGroupService.select(groupUser);
        if (accUserGroupList == null || accUserGroupList.size() < 1) {
            groupUser.setGroupId(registerDto.getGroupId());
            accUserGroupService.save(groupUser);
        }

        AccEmployeeGroup accEmployeeGroup = new AccEmployeeGroup();
        accEmployeeGroup.setEmployeeGroupId(generateId());
        accEmployeeGroup.setUserId(id);
        accEmployeeGroup.setGroupId(registerDto.getGroupId());
        accEmployeeGroup.setEmployeeCode("000");
        accEmployeeGroup.setEmployeeStatus((byte)0);
        accEmployeeGroup.setEmployeeType(registerDto.getEmployeeType());
        accEmployeeGroupService.save(accEmployeeGroup);
    }

        @Override
    public void activeUser(String activeUserToken) {
        Preconditions.checkArgument(!StringUtils.isEmpty(activeUserToken), "激活用户失败");

        String activeUserKey = RedisKeyUtil.getActiveUserKey(activeUserToken);

        String email = redisService.getKey(activeUserKey);

        if (StringUtils.isEmpty(email)) {
            throw new UacBizException(ErrorCodeEnum.UAC10011030);
        }
        // 修改用户状态, 绑定访客角色
        AccUser accUser = new AccUser();
        accUser.setEmail(email);

        accUser = accUserMapper.selectOne(accUser);
        if (accUser == null) {
            logger.error("找不到用户信息. email={}", email);
            throw new UacBizException(ErrorCodeEnum.UAC10011004, email);
        }

        AccUser update = new AccUser();
        update.setUserId(accUser.getUserId());
//        update.setStatus(AccUserStatusEnum.ENABLE.getValue());
        update.setIsEnable(true);
        LoginAuthDto loginAuthDto = new LoginAuthDto();
        loginAuthDto.setUserId(accUser.getUserId());
        loginAuthDto.setUserName(accUser.getLoginName());
        loginAuthDto.setLoginName(accUser.getLoginName());
        update.setUpdateTime(new Date());

        AccUser user = this.queryByUserId(accUser.getUserId());

        Map<String, Object> param = Maps.newHashMap();
        param.put("loginName", user.getLoginName());
        param.put("dateTime", DateUtil.formatDateTime(new Date()));

        Set<String> to = Sets.newHashSet();
        to.add(user.getEmail());


        RabbitMetaMessage mqMessageData = emailProducer.sendEmailMq(to, UacEmailTemplateEnum.ACTIVE_USER_SUCCESS, param);
        try {
            userManager.activeUser(mqMessageData, update, activeUserKey);
        } catch (Exception e) {
            logger.error("激活用户失败，error={}", e.getMessage());
        }
    }

    private void validateRegisterInfo(UserRegisterDto registerDto) {
        String mobileNo = registerDto.getMobileNo();

        Preconditions.checkArgument(!StringUtils.isEmpty(registerDto.getLoginName()), ErrorCodeEnum.UAC10011007.msg());
        // 暂时屏蔽掉邮件注册功能 del by wg 20181201
//        Preconditions.checkArgument(!StringUtils.isEmpty(registerDto.getEmail()), ErrorCodeEnum.UAC10011018.msg());
        Preconditions.checkArgument(!StringUtils.isEmpty(mobileNo), "手机号不能为空");
        Preconditions.checkArgument(!StringUtils.isEmpty(registerDto.getLoginPwd()), ErrorCodeEnum.UAC10011014.msg());
        Preconditions.checkArgument(!StringUtils.isEmpty(registerDto.getConfirmPwd()), ErrorCodeEnum.UAC10011009.msg());
        Preconditions.checkArgument(!StringUtils.isEmpty(registerDto.getRegisterSource()), "验证类型错误");
        Preconditions.checkArgument(registerDto.getLoginPwd().equals(registerDto.getConfirmPwd()), "两次密码不一致");

        AccUser accUser = new AccUser();
        accUser.setLoginName(registerDto.getLoginName());
        int count = accUserMapper.selectCount(accUser);
        if (count > 0) {
            throw new UacBizException(ErrorCodeEnum.UAC10011012);
        }

        accUser = new AccUser();
        accUser.setMobile(registerDto.getMobileNo());
        count = accUserMapper.selectCount(accUser);
        if (count > 0) {
            throw new UacBizException(ErrorCodeEnum.UAC10011013);
        }

        // 暂时屏蔽掉邮件激活功能 del by wg 20181201
        if (!StringUtils.isEmpty(registerDto.getEmail())) {
            accUser = new AccUser();
            accUser.setEmail(registerDto.getEmail());
            count = accUserMapper.selectCount(accUser);
            if (count > 0) {
                throw new UacBizException(ErrorCodeEnum.UAC10011019);
            }
        }

    }

    /**
     * 根据组织ID和仓库管理员的角色ID查找与组织关联仓库的管理员
     *
     * @param groupId
     * @param roleId
     * @return
     */
    @Override
    public List<WarehouseAdminUserDto> findWarehousAdminsByGroupId(Long groupId, Long roleId) {
        Preconditions.checkArgument(groupId != null, "组织id为空");
        Preconditions.checkArgument(roleId != null, "角色id为空");
        return accUserMapper.findWarehousAdminsByGroupId(groupId, roleId);
    }

    @Override
    public int updateIsEmployeeByIds(List<Long> userIds, Boolean isEmployee) {
        if (PublicUtil.isNotEmpty(userIds)) {
            return accUserMapper.updateIsEmployeeByIds(userIds, isEmployee);
        }

        return 0;
    }

    /**
     * 修改用户类型
     */
    @Override
    public void modifyUserTypeByIds(List<Long> userIds, Long groupType, Boolean status) {
        if (GlobalConstant.Sys.GROUP_CUSTOMER.equals(groupType)) {  // 普通用户不做修改
            return;
        }

        if (PublicUtil.isEmpty(userIds)) {
            return;
        }

        if ((!GlobalConstant.Sys.GROUP_CUSTOMER.equals(groupType)
                && !GlobalConstant.Sys.GROUP_SHOPPER.equals(groupType)
                && !GlobalConstant.Sys.GROUP_SUPPLIER.equals(groupType))) {
            groupType = GlobalConstant.Sys.GROUP_COMPANY;
        }

        Integer userType = 0;
        Boolean isEmployee = null;
        if (status) {  // 设置用户类型
            switch (groupType.intValue()) {
                case 1:
                    userType = GlobalConstant.Sys.USER_TYPE_COMPANY;
                    isEmployee = true;
                    break;
                case 2:
                    userType = GlobalConstant.Sys.USER_TYPE_SUPPLIER;
                    break;
                case 3:
                    userType = GlobalConstant.Sys.USER_TYPE_SHOPPER;
                    break;
                default:
                    break;
            }

            accUserMapper.setUserTypeByIds(userIds, userType, isEmployee);
        } else {  // 取消用户类型
            switch (groupType.intValue()) {
                case 1:
                    userType = ~GlobalConstant.Sys.USER_TYPE_COMPANY;
                    isEmployee = false;
                    break;
                case 2:
                    userType = ~GlobalConstant.Sys.USER_TYPE_SUPPLIER;
                    break;
                case 3:
                    userType = ~GlobalConstant.Sys.USER_TYPE_SHOPPER;
                    break;
                default:
                    break;
            }

            accUserMapper.cancelUserTypeByIds(userIds, userType, isEmployee);
        }
    }

    @Override
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public PageInfo queryUserListWithPage(AccUser accUser) {
        PageHelper.startPage(accUser.getPageNum(), accUser.getPageSize());
        accUser.setOrderBy("u.update_time desc");
        List<AccUser> uacUserList = accUserMapper.selectUserList(accUser);
        //todo 实现按后台登录groupId分组显示

        return new PageInfo<>(uacUserList);
    }

    @Override
    public int modifyUserStatusById(AccUser accUser, LoginAuthDto authResDto) {
        Long loginUserId = authResDto.getUserId();
        Long userId = accUser.getUserId();
        if (loginUserId.equals(userId)) {
            throw new UacBizException(ErrorCodeEnum.UAC10011023);
        }
        AccUser u = accUserMapper.selectByPrimaryKey(userId);
        if (u == null) {
            throw new UacBizException(ErrorCodeEnum.UAC10011011, userId);
        }

        // 更新用户最后修改人与修改时间
        accUser.setUpdateTime(new Date());
        return accUserMapper.updateByPrimaryKeySelective(accUser);
    }

    private Integer getUserTypeByGroupId(Long groupId) {
        Integer userType = GlobalConstant.Sys.USER_TYPE_CUSTOMER;

        if (groupId != null) {
            switch (groupId.intValue()) {
                case 2:
                    userType = GlobalConstant.Sys.USER_TYPE_SUPPLIER;
                    break;
                case 3:
                    userType = GlobalConstant.Sys.USER_TYPE_SHOPPER;
                    break;
                default:
                    userType = GlobalConstant.Sys.USER_TYPE_COMPANY;
                    break;
            }
        }

        return userType;
    }

    @Override
    public void saveAccUser(AccUser user, LoginAuthDto loginAuthDto) {
        //保存用户信息
        String loginName = user.getLoginName();

        // mod by wg 20181203 修改用户时用户名应该放到新增中
//        Preconditions.checkArgument(!StringUtils.isEmpty(loginName), "用户名不能为空");
//        Preconditions.checkArgument(user.getGroupId() != null, "组织不能为空");  // 组织为空时，用户为普通用户

        if (null == user.getUserId()) {
            Preconditions.checkArgument(!StringUtils.isEmpty(loginName), "用户名不能为空");

            user.setCreateTime(new Date());

            String loginPwd = user.getUserPassword();
            Preconditions.checkArgument(!StringUtils.isEmpty(loginPwd), ErrorCodeEnum.UAC10011014.msg());

            user.setUserPassword(Md5Util.encrypt(loginPwd));
            user.setPayPassword(Md5Util.encrypt(user.getMobile()));//20191216 添加手机号码作为支付密码
            // 验证用户名是否存在
            AccUser query = new AccUser();
            query.setLoginName(loginName);
            int count = accUserMapper.selectCount(query);
            if (count > 0) {
                throw new UacBizException(ErrorCodeEnum.UAC10011025, loginName);
            }
            Long userId = super.generateId();
            // 1.保存用户信息
            user.setUserId(userId);
            user.setLoginName(loginName);
            Integer userType = getUserTypeByGroupId(user.getGroupId());
            user.setType(userType.byteValue());

            Boolean isEmployee = user.getIsEmployee();
            if (isEmployee == null) {
                if (userType == GlobalConstant.Sys.USER_TYPE_COMPANY) {
                    isEmployee = true;
                } else {
                    isEmployee = false;
                }
            }
            user.setIsEmployee(isEmployee);

            user.setUserSource(AccUserSourceEnum.INSERT.getKey());
            // TODO 校验状态是否合法
            accUserMapper.insertSelective(user);

            // 2.添加组织关联
            if (PublicUtil.isNotEmpty(user.getGroupId())) {
                AccUserGroup groupUser = new AccUserGroup();
                groupUser.setGroupId(user.getGroupId());
                groupUser.setUserId(userId);
                groupUser.setEmployeeCode(user.getEmployeeCode());
                log.info("saveAccUser-> user.getGroupId()={}->accUserGroupService.save(groupUser);", user.getGroupId());
                logger.info("saveAccUser-> user.getGroupId(){}->accUserGroupService.save(groupUser);", user.getGroupId());
                accUserGroupService.save(groupUser);
            } else {
                AccUserGroup groupUser = new AccUserGroup();
                groupUser.setGroupId(GlobalConstant.Sys.GROUP_CUSTOMER);
                groupUser.setUserId(userId);
                groupUser.setEmployeeCode(user.getEmployeeCode());
                System.out.println("没找到user.getGroupId()，默认填入4");
                log.info("saveAccUser-> user.getGroupId()，默认填入4->accUserGroupService.save(groupUser);");
                logger.info("saveAccUser-> user.getGroupId()，默认填入4->accUserGroupService.save(groupUser);");
                accUserGroupService.save(groupUser);
            }

            //todo 注册用户是否需要添加默认的角色？
            // 绑定一个访客角色默认值 add by wg 20181203
            accUserRoleService.saveRoleUser(userId, GlobalConstant.Sys.CONSUMER_ROLE_ID);
            //todo 注册用户发张C 端优惠券，新人优惠券满200减20？
            cmcFeignApi.addCouponReceive(userId, 5, 2);
        } else {
            user.setUpdateTime(new Date());

            AccUser accUser = accUserMapper.selectByPrimaryKey(user.getUserId());
            Preconditions.checkArgument(accUser != null, "用户不存在");
            // 1.更新用户信息
            int updateInt = accUserMapper.updateByPrimaryKeySelective(user);
            if (updateInt < 1) {
                throw new UacBizException(ErrorCodeEnum.UAC10011026, user.getUserId());
            }

        }

        //保存或修改用户详细信息
        if (!PublicUtil.isEmpty(user.getAccUserInfoDto())) {
            AccUserInfo accUserInfo = new AccUserInfo();
            BeanUtils.copyProperties(user.getAccUserInfoDto(), accUserInfo);
            accUserInfo.setUserId(user.getUserId());
            this.saveUserInfo(accUserInfo);
        }

    }

    /**
     * 用户详细信息保存
     */
    private void saveUserInfo(AccUserInfo accUserInfo) {
        if (PublicUtil.isEmpty(accUserInfo)) {
            return;
        }

        Preconditions.checkArgument(!StringUtils.isEmpty(accUserInfo.getUserId()), "用户ID不能为空");

        //先判断记录是新增还是修改
        Example example = new Example(AccUserInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId", accUserInfo.getUserId());

        int result = accUserInfoService.selectCountByExample(example);

        if (result == 0) {  // 新增
            Long userInfoId = super.generateId();
            accUserInfo.setUserInfoId(userInfoId);
            accUserInfoService.save(accUserInfo);
        } else {  //修改
            Example exampleMod = new Example(AccUserInfo.class);
            Example.Criteria criteriaMod = exampleMod.createCriteria();
            criteriaMod.andEqualTo("userId", accUserInfo.getUserId());
            accUserInfo.setUpdateTime(new Date());
            accUserInfoService.updateByExample(accUserInfo, exampleMod);
        }
    }

    @Override
    public int userModifyPwd(UserModifyPwdDto userModifyPwdDto, LoginAuthDto authResDto) {
        String loginName = userModifyPwdDto.getLoginName();
        String oldPassword = userModifyPwdDto.getOldPassword();
        String newPassword = userModifyPwdDto.getNewPassword();
        String confirmPwd = userModifyPwdDto.getConfirmPwd();

        Preconditions.checkArgument(!PublicUtil.isEmpty(loginName), ErrorCodeEnum.UAC10011007.msg());
        Preconditions.checkArgument(!PublicUtil.isEmpty(oldPassword), "原始密码不能为空");
        Preconditions.checkArgument(!PublicUtil.isEmpty(newPassword), "新密码不能为空");
        Preconditions.checkArgument(!PublicUtil.isEmpty(confirmPwd), ErrorCodeEnum.UAC10011009.msg());
        Preconditions.checkArgument(newPassword.equals(confirmPwd), "两次密码不一致, 请重新输入！");


        AccUser user = accUserMapper.findByLoginName(loginName);
        if (PublicUtil.isEmpty(user)) {
            throw new UacBizException(ErrorCodeEnum.UAC10011002, loginName);
        }

        String oldPwd = user.getUserPassword();
        String newEncrypt = Md5Util.encrypt(newPassword);

        if (!Md5Util.matches(oldPassword, oldPwd)) {
            throw new UacBizException(ErrorCodeEnum.UAC10011035);
        }

        AccUser accUser = new AccUser();
        if (Md5Util.matches(newPassword, oldPwd)) {
            throw new UacBizException(ErrorCodeEnum.UAC10011036);
        }

//        accUser.setUserPassword(Md5Util.encrypt(newPassword));
        accUser.setUserId(user.getUserId());
        accUser.setUserPassword(newEncrypt);
        // 该用户已经修改过密码
        accUser.setIsChangedPwd(true);
        accUser.setUpdateTime(new Date());

        return accUserMapper.updateByPrimaryKeySelective(accUser);

        // TODO 发送重置密码成功的邮件
    }

    @Override
    public int userModifyPayPwd(UserModifyPwdDto userModifyPwdDto, LoginAuthDto authResDto) {
        String loginName = userModifyPwdDto.getLoginName();
        String oldPassword = userModifyPwdDto.getOldPassword();
        String newPassword = userModifyPwdDto.getNewPassword();
        String confirmPwd = userModifyPwdDto.getConfirmPwd();

        Preconditions.checkArgument(!PublicUtil.isEmpty(loginName), ErrorCodeEnum.UAC10011007.msg());
        Preconditions.checkArgument(!PublicUtil.isEmpty(oldPassword), "原始密码不能为空");
        Preconditions.checkArgument(!PublicUtil.isEmpty(newPassword), "新密码不能为空");
        Preconditions.checkArgument(!PublicUtil.isEmpty(confirmPwd), ErrorCodeEnum.UAC10011009.msg());
        Preconditions.checkArgument(newPassword.equals(confirmPwd), "两次密码不一致, 请重新输入！");


        AccUser user = accUserMapper.findByLoginName(loginName);
        if (PublicUtil.isEmpty(user)) {
            throw new UacBizException(ErrorCodeEnum.UAC10011002, loginName);
        }

        String oldPwd = user.getPayPassword();
        String newEncrypt = Md5Util.encrypt(newPassword);

        if (!Md5Util.matches(oldPassword, oldPwd)) {
            throw new UacBizException(ErrorCodeEnum.UAC10011035);
        }

        AccUser accUser = new AccUser();
        if (Md5Util.matches(newPassword, oldPwd)) {
            throw new UacBizException(ErrorCodeEnum.UAC10011036);
        }

        accUser.setUserId(user.getUserId());
        accUser.setPayPassword(newEncrypt);

        accUser.setUpdateTime(new Date());

        return accUserMapper.updateByPrimaryKeySelective(accUser);

    }

    // 修改手机号
    @Override
    public int userModifyMobileNo(ModifyUserMobile modifyUserMobile, LoginAuthDto authResDto) {
        Long userId = modifyUserMobile.getUserId();
        String mobileNo = modifyUserMobile.getMobile();

        Preconditions.checkArgument(userId != null, "用户ID不能为空");
        Preconditions.checkArgument(!PublicUtil.isEmpty(mobileNo), "手机号码不能为空");
        Preconditions.checkArgument(PubUtils.isMobileNumber(mobileNo), "手机号码格式不正确");

        // 检查手机是否已经注册
        Example example = new Example(AccUser.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("mobile", mobileNo);

        int result = accUserMapper.selectCountByExample(example);
        if (result > 0) {
//            throw new UacBizException(ErrorCodeEnum.UAC10011013);
            return -1;
        }

        AccUser accUser = new AccUser();
        accUser.setUserId(userId);
        accUser.setMobile(mobileNo);
        accUser.setUpdateTime(new Date());

        return accUserMapper.updateByPrimaryKeySelective(accUser);
    }

    @Override
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public List<AccUser> findUserInfoByUserIds(List<Long> userIds) {
        return accUserMapper.selectUserInfoByUserIds(userIds);
    }

    @Override
    public int userModifyPwdByPhone(UserModifyPwdByPhoneDto userModifyPwdByPhoneDto) {
        String mobile = userModifyPwdByPhoneDto.getMobile();
        String newPassword = userModifyPwdByPhoneDto.getNewPassword();
        String confirmPwd = userModifyPwdByPhoneDto.getConfirmPwd();

        Preconditions.checkArgument(!PublicUtil.isEmpty(mobile), ErrorCodeEnum.UAC10011006.msg());
        Preconditions.checkArgument(!PublicUtil.isEmpty(newPassword), "新密码不能为空");
        Preconditions.checkArgument(!PublicUtil.isEmpty(confirmPwd), ErrorCodeEnum.UAC10011009.msg());
        Preconditions.checkArgument(newPassword.equals(confirmPwd), "两次密码不一致, 请重新输入！");

        AccUser user = this.findByMobileNo(mobile);

        if (PublicUtil.isEmpty(user)) {
            throw new UacBizException(ErrorCodeEnum.UAC10011027, mobile);
        }

        String newEncrypt = Md5Util.encrypt(newPassword);

        AccUser accUser = new AccUser();

        accUser.setUserId(user.getUserId());
        accUser.setUserPassword(newEncrypt);
        // 该用户已经修改过密码
        accUser.setIsChangedPwd(true);
        accUser.setUpdateTime(new Date());

        return accUserMapper.updateByPrimaryKeySelective(accUser);
    }

    /**
     * 修改用户类型为店铺或供应商
     *
     * @param userId
     * @param userType
     * @param isSet    true:设置，false: 取消
     * @return
     */
    @Override
    public void modifyUserTypeToSellerOrSupplier(Long userId, Integer userType, Boolean isSet) {

        Preconditions.checkArgument(!StringUtils.isEmpty(userId), "用户ID不能为空");
        Preconditions.checkArgument(!StringUtils.isEmpty(userType), "用户类型不能为空");


        Long roleId = 0L;

        if (GlobalConstant.Sys.USER_TYPE_SHOPPER == userType) {
            roleId = GlobalConstant.Sys.SELLER_ROLE_ID;
            if (!isSet) {
                userType = ~GlobalConstant.Sys.USER_TYPE_SHOPPER;
            }
        } else if (GlobalConstant.Sys.USER_TYPE_SUPPLIER == userType) {
            roleId = GlobalConstant.Sys.SUPPLIER_ROLE_ID;
            if (!isSet) {
                userType = ~GlobalConstant.Sys.USER_TYPE_SUPPLIER;
            }
        } else {
            throw new UacBizException(ErrorCodeEnum.GL99990100);
        }

        // 修改用户表user的用户类型type
        List<Long> userIds = new ArrayList<>();
        userIds.add(userId);
        accUserMapper.setUserTypeByIds(userIds, userType, false);

        // 绑定/取消组织  在申请店铺时已经绑定组织部门所以取消
//        Example example = new Example(AccUserGroup.class);
//        Example.Criteria criteria = example.createCriteria();
//        criteria.andEqualTo("userId", userId);//.andEqualTo("groupId", groupId);
//        AccUserGroup userGroup = accUserGroupMapper.selectOneByExample(example);
//        if (PublicUtil.isEmpty(userGroup) && isSet) {
//            AccUserGroup accUserGroup = new AccUserGroup();
//            accUserGroup.setGroupId(groupId);
//            accUserGroup.setUserId(userId);
//
//            accUserGroupMapper.insertSelective(accUserGroup);
//        } else if (!PublicUtil.isEmpty(userGroup) && !isSet) {
//            //userGroup.setGroupId()
//            //accUserGroupMapper.updateByPrimaryKey(userGroup);
//        }

        // 绑定/取消角色
        Example example1 = new Example(AccUserRole.class);
        Example.Criteria criteria1 = example1.createCriteria();
        criteria1.andEqualTo("userId", userId).andEqualTo("roleId", roleId);

        AccUserRole userRole = accUserRoleMapper.selectOneByExample(example1);
        if (PublicUtil.isEmpty(userRole) && isSet) {
            AccUserRole accUserRole = new AccUserRole();
            accUserRole.setUserRoleId(generateId());
            accUserRole.setUserId(userId);
            accUserRole.setRoleId(roleId);
            accUserRoleMapper.insertSelective(accUserRole);
        } else if (!PublicUtil.isEmpty(userRole) && !isSet) {
            accUserRoleMapper.deleteByExample(example1);
        }
    }

    @Override
    public List<AccUser> GetUserListByShop(Long shopId, String loginName, String userName, String mobile) {
        Example example = new Example(AccUser.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("referenceShopId", shopId);

        if (PublicUtil.isNotEmpty(loginName)) {
            criteria.andEqualTo("loginName", loginName);
        }
        if (PublicUtil.isNotEmpty(userName)) {
            criteria.andEqualTo("userName", userName);
        }
        if (PublicUtil.isNotEmpty(mobile)) {
            criteria.andEqualTo("mobile", mobile);
        }

        // 指定查询的属性列
        example.selectProperties("userId", "isEnable", "loginName", "userName", "mobile", "nickname", "headImgUri", "referenceShopId", "createTime");

        List<AccUser> list = accUserMapper.selectByExample(example);

        return list;
    }

    @Override
    public List<AccUser> selectUserInfoByGroupId(Long groupId) {
        return accUserMapper.selectUserInfoByGroupId(groupId);
    }

    @Override
    public List<AccUser> getFindByLoginName(String loginName) {
        Example example = new Example(AccUser.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andLike("loginName", "%" + loginName + "%");
        List<AccUser> accUsers = selectByExample(example);
        return accUsers;
    }

    @Override
    public List<AccUser> getUserPageByUserIds(List<Long> userIds, Byte userType) {
        return accUserMapper.getUserPageByUserIds(userIds, userType);
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Integer autoRegisterUserAndShop(UserRegisterDto userRegisterDto, String shopName, Long wareHouseId) {


        // 校验注册信息
        String mobileNo = userRegisterDto.getMobileNo();
        Preconditions.checkArgument(!StringUtils.isEmpty(mobileNo), "手机号不能为空");
        Preconditions.checkArgument(!StringUtils.isEmpty(userRegisterDto.getLoginPwd()), ErrorCodeEnum.UAC10011014.msg());
        Preconditions.checkArgument(!StringUtils.isEmpty(userRegisterDto.getConfirmPwd()), ErrorCodeEnum.UAC10011009.msg());
        Preconditions.checkArgument(!StringUtils.isEmpty(userRegisterDto.getRegisterSource()), "验证类型错误");


        AccUser accUser = new AccUser();
        accUser.setMobile(userRegisterDto.getMobileNo());
        int count = accUserMapper.selectCount(accUser);
        if (count > 0) {
            throw new UacBizException(ErrorCodeEnum.UAC10011013);
        }

        Date now = new Date();

        // 封装注册信息
        long id = generateId();
        accUser = new AccUser();
        accUser.setUserPassword(Md5Util.encrypt(userRegisterDto.getLoginPwd()));
        accUser.setMobile(mobileNo);
        accUser.setLoginName(shopName);
        accUser.setUserName(shopName);
        accUser.setPayPassword(Md5Util.encrypt(mobileNo.substring(5,11)));//20191216 设置支付密码初始值为手机号码后6位
        accUser.setIsEnable(true);
        accUser.setUserSource(AccUserSourceEnum.INSERT.getKey());
        accUser.setCreateTime(now);
        accUser.setUpdateTime(now);

        accUser.setUserId(id);
        accUser.setType(GlobalConstant.Sys.USER_TYPE_CUSTOMER.byteValue());  // 注册时默认初始用户类型为普通客户
        accUser.setIsEmployee(false);  // 注册时默认初始用户不为公司用户

        // add by wg 20190422 用户注册时增加推荐人或推荐店铺ID
        if (userRegisterDto.getReferenceId() != null && userRegisterDto.getReferenceId() > 0) {
            accUser.setReferenceId(userRegisterDto.getReferenceId());
        } else if (userRegisterDto.getReferenceShopId() != null && userRegisterDto.getReferenceShopId() > 0) {
            accUser.setReferenceShopId(userRegisterDto.getReferenceShopId());
        }

        // 生产用户账号
        Integer kk = accUserMapper.insertSelective(accUser);  //

        // 绑定一个访客角色默认值
        accUserRoleService.saveRoleUser(id, GlobalConstant.Sys.CONSUMER_ROLE_ID);

        AccUserGroup groupUser = new AccUserGroup();

        groupUser.setUserId(id);
        List<AccUserGroup> accUserGroupList = accUserGroupService.select(groupUser);
        if (accUserGroupList == null || accUserGroupList.size() <1 ){
            groupUser.setGroupId(GlobalConstant.Sys.GROUP_CUSTOMER);
            log.info("注册时regist-> user.getGroupId()，默认填入4->accUserGroupService.save(groupUser);");
            accUserGroupService.save(groupUser);
        }

        //查询仓库
        ArrayList<Long> wareHouseIds = new ArrayList<>();
        wareHouseIds.add(wareHouseId);
        List<WarehouseInfoDto> result = wmcStorageFeignApi.getWarehouseInfo(wareHouseIds).getResult();

        //保存商店
        Integer num = 0;
        ShopInfoDto shopInfoDto = new ShopInfoDto();
        if (result != null && result.size() == 1 ) {
            WarehouseInfoDto warehouseInfoDto = result.get(0);
            shopInfoDto.setShopName(shopName);
            shopInfoDto.setUserId(accUser.getUserId());
            shopInfoDto.setUserName(accUser.getUserName());
            shopInfoDto.setMobile(accUser.getMobile());
            shopInfoDto.setRegionCityId(warehouseInfoDto.getRegionCityId());
            shopInfoDto.setRegionProvinceId(warehouseInfoDto.getRegionProvinceId());
            shopInfoDto.setRegionCountryId(warehouseInfoDto.getRegionCountryId());
            shopInfoDto.setRegionCountyId(warehouseInfoDto.getRegionCountyId());
            shopInfoDto.setLongitude(warehouseInfoDto.getLongitude());
            shopInfoDto.setLatitude(warehouseInfoDto.getLatitude());
            shopInfoDto.setAddress(userRegisterDto.getAddress());
            shopInfoDto.setWarehouseId(wareHouseId);
            if (kk.equals(1)){
                //保存店铺信息
                num = smcFeignApi.addShop(shopInfoDto);
                //保存收货地址
                accDeliveryAddressService.saveUserDeliveryAddress(shopInfoDto);
            }


            if (!num.equals(1)) {
                //商店保存失败
                throw new UacBizException(ErrorCodeEnum.SMC100600001);
            }else{
                accUserRoleService.saveRoleUser(id, GlobalConstant.Sys.SELLER_ROLE_ID);
            }
        } else {
            //未查询到仓库
            throw new UacBizException(ErrorCodeEnum.GL99990100);
        }

        return num;
    }


    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Long autoRegisterUser(UserRegisterDto userRegisterDto) {

        // 校验注册信息
        String mobileNo = userRegisterDto.getMobileNo();
        Preconditions.checkArgument(!StringUtils.isEmpty(mobileNo), "手机号不能为空");
        Preconditions.checkArgument(!StringUtils.isEmpty(userRegisterDto.getLoginPwd()), ErrorCodeEnum.UAC10011014.msg());
        Preconditions.checkArgument(!StringUtils.isEmpty(userRegisterDto.getConfirmPwd()), ErrorCodeEnum.UAC10011009.msg());
        Preconditions.checkArgument(!StringUtils.isEmpty(userRegisterDto.getRegisterSource()), "验证类型错误");


        AccUser accUser = new AccUser();
        accUser.setMobile(userRegisterDto.getMobileNo());
        int count = accUserMapper.selectCount(accUser);
        if (count > 0) {
            throw new UacBizException(ErrorCodeEnum.UAC10011013);
        }

        Date now = new Date();

        // 封装注册信息
        long id = generateId();
        accUser = new AccUser();
        accUser.setUserPassword(Md5Util.encrypt(userRegisterDto.getLoginPwd()));
        accUser.setMobile(mobileNo);
        accUser.setLoginName(userRegisterDto.getLoginName());
        accUser.setUserName(userRegisterDto.getLoginName());
        accUser.setPayPassword(Md5Util.encrypt(mobileNo.substring(5, 11)));//20191216 设置支付密码初始值为手机号码后6位
        accUser.setIsEnable(true);
        accUser.setUserSource(AccUserSourceEnum.INSERT.getKey());
        accUser.setCreateTime(now);
        accUser.setUpdateTime(now);

        accUser.setUserId(id);
        accUser.setType(GlobalConstant.Sys.USER_TYPE_CUSTOMER.byteValue());  // 注册时默认初始用户类型为普通客户
        accUser.setIsEmployee(false);  // 注册时默认初始用户不为公司用户

        // add by wg 20190422 用户注册时增加推荐人或推荐店铺ID
        if (userRegisterDto.getReferenceId() != null && userRegisterDto.getReferenceId() > 0) {
            accUser.setReferenceId(userRegisterDto.getReferenceId());
        } else if (userRegisterDto.getReferenceShopId() != null && userRegisterDto.getReferenceShopId() > 0) {
            accUser.setReferenceShopId(userRegisterDto.getReferenceShopId());
        }

        // 生产用户账号
        Integer kk = accUserMapper.insertSelective(accUser);  //

        if (kk > 0){
            // 绑定一个访客角色默认值
            accUserRoleService.saveRoleUser(id, GlobalConstant.Sys.CONSUMER_ROLE_ID);
            return id;
        }else{
            return 0L;
        }
    }


}
